﻿using System;
using System.Xml.Linq;

namespace Adjunct.Framework.NuGet
{
	public class NugetConfig
	{
		private readonly XDocument _document;
		private readonly string _path;
		private XElement _settings;

		public NugetConfig(string path = null)
		{
			_path = path;
			_document = (path != null) ? XDocument.Load(_path) : XDocument.Parse("<settings />");
		}

		public string RepositoryPath
		{
			get
			{
				XElement element = Settings.Element("repositoryPath");
				return (element == null) ? string.Empty : element.Value;
			}
			set
			{
				XElement element = Settings.Element("repositoryPath");
				if (element == null)
				{
					element = new XElement("repositoryPath", value);
					Settings.Add(element);
				}
				else
				{
					element.Value = value;
				}
			}
		}

		private XElement Settings
		{
			get
			{
				if (_settings == null)
				{
					_settings = _document.Root;
					if ((_settings == null) || (_settings.Name != "settings"))
					{
						throw new Exception("not a valid nuget.config");
					}
				}
				return _settings;
			}
		}

		public void Save(string pathOverride = null)
		{
			string saveTo = pathOverride ?? _path;
			if (saveTo == null)
			{
				throw new Exception("No path specified to save the nuget.config file to.");
			}
			_document.Save(saveTo);
		}
	}
}